﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace whut_jwc
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        #region 动态生成控件的声明
        Label lblUserInfo = new Label();
        Label[,] lblTable = new Label[8, 6];
        TextBox txtWeek = new TextBox();
        Label lblTableAreaInfo = new Label();
        #endregion

        /// <summary>
        /// 窗体构造函数
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            setColors();

            #region + (lblUserInfo) 生成用户信息文本框，用来登录后替代登录控件区域
            lblUserInfo.Name = "lblUserInfo";
            lblUserInfo.SetValue(Grid.ColumnProperty, 0);
            lblUserInfo.SetValue(Grid.RowProperty, 0);
            Grid.SetColumnSpan(lblUserInfo, 4);
            lblUserInfo.HorizontalAlignment = HorizontalAlignment.Stretch;
            lblUserInfo.VerticalAlignment = VerticalAlignment.Stretch;
            lblUserInfo.HorizontalContentAlignment = HorizontalAlignment.Center;
            lblUserInfo.VerticalContentAlignment = VerticalAlignment.Center;
            lblUserInfo.Content = "";
            lblUserInfo.Margin = lblUsername.Margin;
            lblUserInfo.Visibility = Visibility.Collapsed;
            userInfoArea.Children.Add(lblUserInfo);
            #endregion

            #region + (lblTable[,]) 动态生成课程表 Label 控件（6 行 8 列）
            for (int i = 0; i < 8; i++)
            {
                for (int j = 0; j < 6; j++)
                {
                    lblTable[i, j] = new Label();
                    lblTable[i, j].Name = String.Format("lblTable_{0}_{1}", i, j);
                    lblTable[i, j].SetValue(Grid.ColumnProperty, i);
                    lblTable[i, j].SetValue(Grid.RowProperty, j);
                    lblTable[i, j].FontSize = FontSize * 1.44;
                    lblTable[i, j].HorizontalAlignment = HorizontalAlignment.Stretch;
                    lblTable[i, j].VerticalAlignment = VerticalAlignment.Stretch;
                    lblTable[i, j].HorizontalContentAlignment = HorizontalAlignment.Center;
                    lblTable[i, j].VerticalContentAlignment = VerticalAlignment.Center;
                    lblTable[i, j].Content = "";
                    lblTable[i, j].Margin = new Thickness(0, 0, 0, 0);
                    lblTable[i, j].AddHandler(MouseWheelEvent, new MouseWheelEventHandler(lblTable_MouseWheel));
                    tableArea.Children.Add(lblTable[i, j]);
                }
            }
            #endregion

            #region + (txtWeek) 生成周数文本框，用来替代表格左上角的 Label
            txtWeek.Name = "txtWeek";
            txtWeek.SetValue(Grid.ColumnProperty, 0);
            txtWeek.SetValue(Grid.RowProperty, 0);
            txtWeek.FontSize = lblTable[0, 0].FontSize;
            txtWeek.HorizontalAlignment = lblTable[0, 0].HorizontalAlignment;
            txtWeek.VerticalAlignment = lblTable[0, 0].VerticalAlignment;
            txtWeek.HorizontalContentAlignment = lblTable[0, 0].HorizontalContentAlignment;
            txtWeek.VerticalContentAlignment = lblTable[0, 0].VerticalContentAlignment;
            txtWeek.Text = gWeekNum.ToString();
            txtWeek.Margin = lblTable[0, 0].Margin;
            txtWeek.Visibility = Visibility.Collapsed;
            txtWeek.AddHandler(KeyDownEvent, new KeyEventHandler(txtWeek_KeyDown));
            tableArea.Children.Add(txtWeek);
            #endregion

            #region > (lblTable[,]) 设置课程表标题区域的 Label 控件属性
            lblTable[0, 0].Content = String.Format("第 {0} 周", gWeekNum);
            lblTable[0, 0].AddHandler(MouseDownEvent, new MouseButtonEventHandler(week_MouseDown));

            lblTable[0, 1].Content = "1 - 2";
            lblTable[0, 2].Content = "3 - 4";
            lblTable[0, 3].Content = "5 - 6";
            lblTable[0, 4].Content = "7 - 8";
            lblTable[0, 5].Content = "9 - 11";
            for (int i = 0; i <= 5; i++)
                lblTable[0, i].Background = new SolidColorBrush(Color.FromRgb(240, 240, 240));
            lblTable[1, 0].Content = "一";
            lblTable[2, 0].Content = "二";
            lblTable[3, 0].Content = "三";
            lblTable[4, 0].Content = "四";
            lblTable[5, 0].Content = "五";
            lblTable[6, 0].Content = "六";
            lblTable[7, 0].Content = "日";
            for (int i = 1; i <= 7; i++)
                lblTable[i, 0].Background = new SolidColorBrush(Color.FromRgb(240, 240, 240));
            #endregion

            #region + (lblTableAreaInfo) 生成课程表内容区域提示信息
            lblTableAreaInfo.Name = "lblTableAreaInfo";
            lblTableAreaInfo.SetValue(Grid.ColumnProperty, 1);
            lblTableAreaInfo.SetValue(Grid.RowProperty, 1);
            Grid.SetColumnSpan(lblTableAreaInfo, 7);
            Grid.SetRowSpan(lblTableAreaInfo, 5);
            lblTableAreaInfo.HorizontalAlignment = HorizontalAlignment.Stretch;
            lblTableAreaInfo.VerticalAlignment = VerticalAlignment.Stretch;
            lblTableAreaInfo.HorizontalContentAlignment = HorizontalAlignment.Center;
            lblTableAreaInfo.VerticalContentAlignment = VerticalAlignment.Center;
            lblTableAreaInfo.FontSize = lblTable[0, 0].FontSize;
            lblTableAreaInfo.Content = "";
            lblTableAreaInfo.Margin = new Thickness(0, 0, 0, 0);
            lblTableAreaInfo.Visibility = Visibility.Collapsed;
            tableArea.Children.Add(lblTableAreaInfo);
            #endregion

            SetTableInfoArea(0);
        }

        private void txtWeek_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Enter :
                    try
                    {
                        gWeekNum = int.Parse(txtWeek.Text);
                    }
                    catch { }
                    finally
                    {
                        lblTable[0, 0].Content = String.Format("第 {0} 周", gWeekNum);
                        txtWeek.Visibility = Visibility.Collapsed;
                        lblTable[0, 0].Visibility = Visibility.Visible;
                    }
                    break;
                case Key.Escape:
                    txtWeek.Visibility = Visibility.Collapsed;
                    lblTable[0, 0].Visibility = Visibility.Visible;
                    break;
            }
            UpdateTable();
        }

        private void week_MouseDown(object sender, MouseButtonEventArgs e)
        {
            txtWeek.Text = gWeekNum.ToString();
            lblTable[0, 0].Visibility = Visibility.Collapsed;
            txtWeek.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 将中文的星期转为数字
        /// </summary>
        public static Dictionary<string, int> weekdayDictionary = new Dictionary<string, int>
        {
            { "日", 0 }, { "一", 1 }, { "二", 2 }, { "三", 3 },
            { "四", 4 }, { "五", 5 }, { "六", 6 }
        };

        public static List<Color> colors = new List<Color>();

        /// <summary>
        /// 设置颜色列表（用于课程表单元格背景色）
        /// </summary>
        private void setColors()
        {
            colors.Add(Color.FromRgb(250, 125, 141));
            colors.Add(Color.FromRgb(3, 179, 240));
            colors.Add(Color.FromRgb(20, 101, 155));
            colors.Add(Color.FromRgb(188, 138, 225));
            colors.Add(Color.FromRgb(255, 186, 8));
            colors.Add(Color.FromRgb(147, 197, 8));
            colors.Add(Color.FromRgb(112, 159, 249));
            colors.Add(Color.FromRgb(255, 141, 66));
            colors.Add(Color.FromRgb(229, 119, 196));
            colors.Add(Color.FromRgb(254, 67, 101));
            colors.Add(Color.FromRgb(252, 157, 154));
            colors.Add(Color.FromRgb(249, 205, 173));
            colors.Add(Color.FromRgb(200, 200, 169));
            colors.Add(Color.FromRgb(131, 175, 155));
        }

        bool isLoggedin = false;
        int gWeekNum = 1;
        int maxWeek = 1;
        Dictionary<string, List<int[]>> gTimeDict = new Dictionary<string, List<int[]>>();
        Dictionary<string, string[]> gPlaceDict = new Dictionary<string, string[]>();
        Dictionary<string, string> gTeacherDict = new Dictionary<string, string>();
        Dictionary<string, Color> lessonColor = new Dictionary<string, Color>();

        /// <summary>
        /// 登录教务处，返回 HTML
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>HTML（如果出现异常则为 null）</returns>
        private string LoginJwc(string username, string password)
        {
            const string url = "http://sso.jwc.whut.edu.cn/Certification//login.do";
            var result = string.Empty;
            string param = "userName=" + username + "&password=" + password + "&type=xs";
            byte[] postData = Encoding.UTF8.GetBytes(param);
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url) as HttpWebRequest;
                Encoding myEncoding = Encoding.UTF8;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postData.Length;
                request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:51.0) Gecko/20100101 Firefox/51.0";
                request.Host = "sso.jwc.whut.edu.cn";
                request.Referer = "http://sso.jwc.whut.edu.cn/Certification//toIndex.do";
                request.Accept = "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8";
                request.KeepAlive = true;
                Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();
                HttpWebResponse response;
                Stream responseStream;
                StreamReader reader;
                string srcString;
                response = request.GetResponse() as HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
                srcString = reader.ReadToEnd();
                result = srcString;
                reader.Close();
                return result;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 检查登录状态
        /// </summary>
        /// <param name="html">获取的 HTML 源码</param>
        /// <returns>状态码</returns>
        private int CheckLoginStatus(string html)
        {
            if (html == null)
            {
                return -1;
            }
            else
            {
                Regex errMsgRe = new Regex(@"alert\(""用户名或密码错误\\n提示：\(学生/教师\)登录密码错误并无法找回，可到所在学院教学办重置密码""\);");
                if (errMsgRe.Match(html).Success)
                {
                    // 用户名或密码错误
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
        }

        /// <summary>
        /// 解析教务处 HTML，返回课程信息列表
        /// </summary>
        /// <param name="html">获取的教务处网页 HTML 源码</param>
        /// <returns>课程信息列表</returns>
        private List<string[]> ParseJwc(string html)
        {
            List<string[]> @return = new List<string[]>();
            Regex re = new Regex(@"<td>(.*)&nbsp;</td>\W*" +
                                 @"<td>(.*)&nbsp;</td>\W*" +
                                 @"<td>(周[日一二三四五六]第\d+-\d+节\{第.*周};)\W*&nbsp;\W*</td>\W*" +
                                 @"<td>(.*;)&nbsp;</td>\W");
            MatchCollection matchcol = re.Matches(html);
            if (matchcol.Count > 0)
            {
                foreach (Match m in matchcol)
                {
                    string[] tmp = new string[4];
                    for (int i = 1; i <= 4; i++)
                    {
                        tmp[i - 1] = m.Groups[i].Value;
                    }
                    @return.Add(tmp);
                }
            }
            return @return;
        }

        /// <summary>
        /// 解析上课时间字符串
        /// </summary>
        /// <param name="weekStr">上课时间字符串</param>
        /// <returns>包含上课时间信息的列表</returns>
        private List<int[]> ParseWeek(string weekStr)
        {
            List<int[]> @return = new List<int[]>();
            string[] weekStrArray = weekStr.Split(';');
            Regex weekRx = new Regex(@"^周([日一二三四五六])第(\d+)-(\d+)节\{第(\d+)-(\d+)[单双]?周}$");
            Match weekRxMatch;
            for (int i = 0; i < weekStrArray.Length - 1; i++)
            {
                string item = weekStrArray[i];
                int evenOdd = 0;
                if (Regex.Match(item, @"单").Success)
                    evenOdd = 1;  // 单周
                else if (Regex.Match(item, @"双").Success)
                    evenOdd = 2;  // 双周
                else
                    evenOdd = 0;
                weekRxMatch = weekRx.Match(item);
                int[] _tmplist =
                {
                    weekdayDictionary[weekRxMatch.Groups[1].Value],
                    evenOdd,
                    int.Parse(weekRxMatch.Groups[2].Value),
                    int.Parse(weekRxMatch.Groups[3].Value),
                    int.Parse(weekRxMatch.Groups[4].Value),
                    int.Parse(weekRxMatch.Groups[5].Value),
                    i  // index
                };
                if (maxWeek < int.Parse(weekRxMatch.Groups[5].Value))
                {
                    maxWeek = int.Parse(weekRxMatch.Groups[5].Value);
                }
                @return.Add(_tmplist);
            }
            return @return;
        }

        /// <summary>
        /// 解析上课地点字符串
        /// </summary>
        /// <param name="placeStr">上课地点字符串</param>
        /// <returns>包含上课地点信息的数组</returns>
        private string[] ParsePlace(string placeStr)
        {
            string[] placeStrArray = placeStr.Split(';');
            return placeStrArray;
        }

        /// <summary>
        /// 生成课程表
        /// </summary>
        /// <param name="weekNum">第几周</param>
        /// <param name="timeDict">课程时间字典</param>
        /// <param name="placeDict">课程地点字典</param>
        /// <param name="teacherDict">课程老师字典</param>
        /// <returns>课程表 (5 * 7 * 3) 三维数组</returns>
        private string[,,] GenerateWeekCube(
            int weekNum,
            Dictionary<string, List<int[]>> timeDict,
            Dictionary<string, string[]> placeDict = null,
            Dictionary<string, string> teacherDict = null)
        {
            string[,,] @return = new string[5, 7, 3];
            List<string> keys = new List<string>();
            List<List<int[]>> item = new List<List<int[]>>();
            foreach (var key in timeDict.Keys)
            {
                keys.Add(key);
                item.Add(timeDict[key]);
            }
            for (int i = 0; i < item.Count; i++)
            {
                foreach (var subitem in item[i])
                {
                    int weekday = subitem[0];
                    int evenOdd = subitem[1];
                    int classLower = subitem[2];
                    int classUpper = subitem[3];
                    int weekLower = subitem[4];
                    int weekUpper = subitem[5];
                    int index = subitem[6];

                    if (weekday == 0)
                        weekday = 6;
                    else
                        --weekday;
                    if (classUpper > 10)
                        classUpper = 10;
                    if (weekNum < weekLower || weekNum > weekUpper)
                        continue;
                    if ((evenOdd == 1 && (weekNum & 1) == 0) || (evenOdd == 2 && (weekNum & 1) == 1))
                        continue;
                    for (int jie = (classLower - 1) / 2; jie < ((classUpper - 2) / 2 + 1); jie++)
                    {
                        @return[jie, weekday, 0] = keys[i];
                        if (placeDict != null)
                        {
                            @return[jie, weekday, 1] = placeDict[keys[i]][index];
                        }
                        if (teacherDict != null)
                        {
                            @return[jie, weekday, 2] = teacherDict[keys[i]];
                        }
                    }
                }
            }
            return @return;
        }

        /// <summary>
        /// 设置表格
        /// </summary>
        /// <param name="weekCube">课程 (5 * 7 * 3) 三维数组</param>
        private void SetTable(string[,,] weekCube)
        {
            for (int column = 0; column < 7; column++)
            {
                for (int row = 0; row < 5; row++)
                {
                    List<string> showItemList = new List<string>();
                    showItemList.Add(weekCube[row, column, 0]);
                    if (weekCube[row, column, 1] != null)
                    {
                        showItemList.Add("@" + weekCube[row, column, 1]);
                    }
                    if (weekCube[row, column, 2] != null)
                    {
                        showItemList.Add(weekCube[row, column, 2]);
                    }
                    lblTable[column + 1, row + 1].Content = String.Join(Environment.NewLine, showItemList);
                    if (weekCube[row, column, 0] != null)
                    {
                        lblTable[column + 1, row + 1].Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 255));
                        lblTable[column + 1, row + 1].Background = new SolidColorBrush(lessonColor[weekCube[row, column, 0]]);
                    }
                    else
                    {
                        lblTable[column + 1, row + 1].Foreground = Foreground;
                        lblTable[column + 1, row + 1].Background = Background;
                    }
                }
            }
        }

        /// <summary>
        /// 清除表格
        /// </summary>
        private void ClearTable()
        {
            for (int column = 1; column <= 7; column++)
            {
                for (int row = 1; row <= 5; row++)
                {
                    lblTable[column, row].Content = "";
                    lblTable[column, row].Foreground = Foreground;
                    lblTable[column, row].Background = Background;
                }
            }
        }

        /// <summary>
        /// 更新表格
        /// </summary>
        private void UpdateTable()
        {
            string[,,] cube = GenerateWeekCube(gWeekNum, gTimeDict, gPlaceDict, gTeacherDict);
            lblTable[0, 0].Content = String.Format("第 {0} 周", gWeekNum);
            SetTable(cube);
        }

        /// <summary>
        /// 设置登录控件显示
        /// </summary>
        /// <param name="isLogin">是否为登录状态</param>
        private void SetLoginControls(bool isLogin)
        {
            txtUsername.IsEnabled = !isLogin;
            txtPassword.IsEnabled = !isLogin;
            lblUsername.Visibility = isLogin ? Visibility.Collapsed : Visibility.Visible;
            txtUsername.Visibility = isLogin ? Visibility.Collapsed : Visibility.Visible;
            lblPassword.Visibility = isLogin ? Visibility.Collapsed : Visibility.Visible;
            txtPassword.Visibility = isLogin ? Visibility.Collapsed : Visibility.Visible;
            lblUserInfo.Visibility = isLogin ? Visibility.Visible : Visibility.Collapsed;
            btnLogin.Content = isLogin ? "注销" : "登录";
        }

        /// <summary>
        /// 设置表格区域控件显示
        /// </summary>
        /// <param name="status">状态</param>
        private void SetTableInfoArea(int status)
        {
            switch (status)
            {
                case 0:
                    for (int column = 1; column <= 7; column++)
                    {
                        for (int row = 1; row <= 5; row++)
                        {
                            lblTable[column, row].Visibility = Visibility.Collapsed;
                        }
                    }
                    lblTableAreaInfo.Content = "↑↑↑↑↑↑ 用户未登录，请先登录 ↑↑↑↑↑↑";
                    lblTableAreaInfo.Visibility = Visibility.Visible;
                    break;
                case 1:
                    for (int column = 1; column <= 7; column++)
                    {
                        for (int row = 1; row <= 5; row++)
                        {
                            lblTable[column, row].Visibility = Visibility.Collapsed;
                        }
                    }
                    lblTableAreaInfo.Content = "正在加载课程表，请稍候……";
                    lblTableAreaInfo.Visibility = Visibility.Visible;
                    break;
                case 2:
                    for (int column = 1; column <= 7; column++)
                    {
                        for (int row = 1; row <= 5; row++)
                        {
                            lblTable[column, row].Visibility = Visibility.Visible;
                        }
                    }
                    lblTableAreaInfo.Content = "";
                    lblTableAreaInfo.Visibility = Visibility.Collapsed;
                    break;
                case -1:
                    for (int column = 1; column <= 7; column++)
                    {
                        for (int row = 1; row <= 5; row++)
                        {
                            lblTable[column, row].Visibility = Visibility.Collapsed;
                        }
                    }
                    lblTableAreaInfo.Content = "用户名或密码错误，请重新输入！";
                    lblTableAreaInfo.Visibility = Visibility.Visible;
                    txtPassword.Focus();
                    txtPassword.SelectAll();
                    break;
            }
        }

        private bool ValidateLoginFormat()
        {
            string msg = null;
            string username = txtUsername.Text;
            string password = txtPassword.Password;
            bool isUsernameValid = Regex.Match(username, @"\d{13}").Success;
            if (username == "" && password != "")
            {
                msg = "用户名不能为空！";
                txtUsername.Focus();
            }
            else if (username != "" && password == "")
            {
                if (!isUsernameValid)
                {
                    msg = "用户名必须为 13 位数字，且密码不能为空！";
                    txtUsername.Focus();
                    txtUsername.SelectAll();
                }
                else
                {
                    msg = "密码不能为空！";
                    txtPassword.Focus();
                }
            }
            else if (username == "" && password == "")
            {
                msg = "用户名和密码不能为空！";
                txtUsername.Focus();
            }
            else
            {
                if (!isUsernameValid)
                {
                    msg = "用户名必须为 13 位数字！";
                    txtUsername.Focus();
                    txtUsername.SelectAll();
                }
            }
            if (msg != null)
            {
                lblTableAreaInfo.Content = msg;
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 登录 / 注销事件处理（异步）
        /// </summary>
        private async void LoginHandler()
        {
            if (!isLoggedin)
            {
                string username = txtUsername.Text;
                string password = txtPassword.Password;
                string html;

                if (ValidateLoginFormat())
                {
                    lblUserInfo.Content = String.Format("用户 {0}", username);
                    SetLoginControls(true);
                    btnLogin.IsEnabled = false;
                    SetTableInfoArea(1);
                    html = await Task.Run(() => LoginJwc(username, password));
                    int status = CheckLoginStatus(html);
                    switch (status)
                    {
                        case 0:
                            isLoggedin = true;
                            btnLogin.IsEnabled = true;
                            SetTableInfoArea(2);

                            var lessonlist = ParseJwc(html);

                            int pColor = 0;
                            foreach (var item in lessonlist)
                            {
                                gTimeDict.Add(item[0], ParseWeek(item[2]));
                                gPlaceDict.Add(item[0], ParsePlace(item[3]));
                                gTeacherDict.Add(item[0], item[1]);
                                if (pColor < colors.Count)
                                {
                                    lessonColor.Add(item[0], colors[pColor]);
                                    pColor++;
                                }
                                else
                                {
                                    pColor = 0;
                                    lessonColor.Add(item[0], colors[pColor]);
                                }
                            }

                            UpdateTable();
                            break;
                        case 1:
                            isLoggedin = false;
                            SetLoginControls(false);
                            btnLogin.IsEnabled = true;
                            SetTableInfoArea(-1);
                            break;
                    }
                }
            }
            else
            {
                lblUserInfo.Content = "";
                SetLoginControls(false);
                ClearTable();
                gTimeDict.Clear();
                gPlaceDict.Clear();
                gTeacherDict.Clear();
                lessonColor.Clear();
                gWeekNum = 1;
                maxWeek = 1;
                isLoggedin = false;
                SetTableInfoArea(0);
            }
        }

        private void lblTable_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (e.Delta > 0)
            {
                if (gWeekNum < maxWeek)
                {
                    ++gWeekNum;
                }
            }
            else if (e.Delta < 0)
            {
                if (gWeekNum > 1)
                {
                    --gWeekNum;
                }
            }
            UpdateTable();
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            LoginHandler();
        }

        private void Login_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                LoginHandler();
            }
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            txtUsername.Focus();
        }

        private void textBox_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox tbx = sender as TextBox;
            tbx.Background = new SolidColorBrush(Color.FromRgb(238, 249, 255));
        }

        private void passwordBox_GotFocus(object sender, RoutedEventArgs e)
        {
            PasswordBox pbx = sender as PasswordBox;
            pbx.Background = new SolidColorBrush(Color.FromRgb(238, 249, 255));
        }

        private void textBox_LostFocus(object sender, RoutedEventArgs e)
        {
            TextBox tbx = sender as TextBox;
            tbx.Background = Background;
        }

        private void passwordBox_LostFocus(object sender, RoutedEventArgs e)
        {
            PasswordBox pbx = sender as PasswordBox;
            pbx.Background = Background;
        }
    }
}
